package client.tablete.workspace;

import java.io.IOException;
import java.net.InetAddress;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;

import android.os.AsyncTask;



public class Listener extends AsyncTask<Void, Integer, String[]> {
    
	private JmDNS jmdns;
//	private ProgressDialog         mUpdateForecastProgressDialog;
	ListTvs ltvs;
	
//	public Listener(ListTvs ltvs){
//		this.ltvs = ltvs;
//	}
	
	@Override
	protected String[] doInBackground(Void... params) {
		
//	    mUpdateForecastProgressDialog = new ProgressDialog(ltvs);
	    
    	try{
			 jmdns = JmDNS.create(InetAddress.getByName("255.255.255.255"));//InetAddress.getByName("0.0.0.0")
//			 publishProgress(10);
       }catch(IOException e){
			 //TODO
       }
       
       ServiceListener mdnsServiceListener = new ServiceListener() {
   		
   		public void serviceAdded(ServiceEvent serviceEvent) {
   			// Test service is discovered. requestServiceInfo() will trigger serviceResolved() callback.
   			jmdns.requestServiceInfo(serviceEvent.getType(), serviceEvent.getName());
   		}
   		
   		public void serviceRemoved(ServiceEvent serviceEvent) {
   			// Test service is disappeared.
//   			System.out.println("remove serviceListener");
   		}
   		
   		public void serviceResolved(ServiceEvent serviceEvent) {
   			// Test service info is resolved.
//   			String serviceUrl = serviceEvent.getInfo().getInetAddress().getHostAddress();
//   			System.out.println("serviceURL: "+serviceUrl);
   			// serviceURL is usually something like http://192.168.11.2:6666/my-service-name
   		}
       };
//       publishProgress(30);
	  	jmdns.addServiceListener(Constants.SERVICE_TYPE, mdnsServiceListener);
		jmdns.registerServiceType(Constants.SERVICE_TYPE);
	  	ServiceInfo[] infos = jmdns.list(Constants.SERVICE_TYPE);
//	  	publishProgress(50);
	  	
	  	String tvs[] = new String[infos.length];
		for(int i = 0; i<infos.length;i++){
			tvs[i] = infos[i].getName()+" = "+infos[i].getAddress()+":"+infos[i].getPort();
		}
//		publishProgress(90);
		jmdns.removeServiceListener(Constants.SERVICE_TYPE, mdnsServiceListener);
	    try {
			jmdns.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		publishProgress(100);
		return tvs;
    }
	
	@Override
    protected void onPostExecute(String tvs[]) {
    	super.onPostExecute(tvs);
    }
    


 }
